﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Net;
using System.Reflection;
using Newtonsoft.Json;

namespace ZK.Common
{
    public class HttpClientUtil
    {
        /// <summary>
        /// 通过post方式请求接口(无参数)
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string doPostMethodToString(string url)
        {
            Common.Log4.LogManage.WriteInfo("post url:" + url);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "post";
            request.KeepAlive = false;
            request.ContentType = "application/json;charset=UTF-8";
            request.Timeout = 10000;
            HttpWebResponse response = null;
            IConfig.UserInfo userInfo = IConfig.GetSetuserInfo;
            if (string.IsNullOrEmpty(userInfo.Token))
            {
                request.Headers.Add("Authorization", AppConfigHelper.GetAppSettings("Token"));
            }
            else
            {
                request.Headers.Add("Authorization", userInfo.Token);
            }
            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (Exception ex)
            {
                response.Close();
                response.Dispose();
                Log4.LogManage.WriteErr("doPostMethodToString url:" + url + " " + ex.ToString());
                return null;

            }
            string res = getResponseString(response);
            Common.Log4.LogManage.WriteInfo("返回值：" + res);
            return res;
        }
        /// <summary>
        /// 通过post方式请求接口(有参数)
        /// </summary>
        /// <param name="url"></param>
        /// <param name="jsonBody"></param>
        /// <returns></returns>
        public static string doPostMethodToString(string url, string jsonBody)
        {
            Common.Log4.LogManage.WriteInfo("post url:" + url + " para:" + jsonBody);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "post";
            request.KeepAlive = false;
            request.ContentType = "application/json;charset=UTF-8";
            request.Timeout = 10000;
            IConfig.UserInfo userInfo = IConfig.GetSetuserInfo;
            if (string.IsNullOrEmpty(userInfo.Token))
            {
                request.Headers.Add("Authorization", AppConfigHelper.GetAppSettings("Token"));
            }
            else
            {
                request.Headers.Add("Authorization", userInfo.Token);
            }
            if (!string.IsNullOrEmpty(jsonBody))
            {
                var stream = request.GetRequestStream();
                using (var writer = new StreamWriter(stream))
                {
                    writer.Write(jsonBody);
                    writer.Flush();
                }
            }
            HttpWebResponse response = null;
            try
            {
                response = (HttpWebResponse)request.GetResponse();
                // SimpleLog.WriteLog("请求接口地址为:" + url + ".返回数据为:" + response.ToString());
            }
            //catch (WebException e)
            catch (Exception ex)
            {
                response.Close();
                response.Dispose();
                Log4.LogManage.WriteErr("doPostMethodToString url:" + url + " data:" + jsonBody + " " + ex.ToString());
                return null;
            }
            string res = getResponseString(response);
            Common.Log4.LogManage.WriteInfo("返回参数：" + res);
            return res;
        }
        /// <summary>
        /// 通过get方式请求接口
        /// </summary>
        /// <param name="url">请求全地址</param>
        /// <param name="isError">是否返回错误码</param>
        /// <returns>返回响应json字符串</returns>
        public static string doGetMethodToString(string url)
        {
            Common.Log4.LogManage.WriteInfo("get url:" + url);
            string errorStr = string.Empty;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.KeepAlive = false;
            request.ContentType = "application/json;charset=UTF-8;";
            request.Timeout = 10000;
            IConfig.UserInfo userInfo = IConfig.GetSetuserInfo;
            if (string.IsNullOrEmpty(userInfo.Token))
            {
                request.Headers.Add("Authorization", AppConfigHelper.GetAppSettings("Token"));
            }
            else
            {
                request.Headers.Add("Authorization", userInfo.Token);
            }
            HttpWebResponse response = null;
            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (Exception ex)
            {
                response.Close();
                response.Dispose();
                Log4.LogManage.WriteErr("doGetMethodToString url " + url + " " + ex.ToString());
                return null;
            }
            string res = getResponseString(response);
            Common.Log4.LogManage.WriteInfo("返回参数：" + res);
            return res;
        }
        /// <summary>
        ///  将 HttpWebResponse 返回结果转换成 string
        /// </summary>
        /// <param name="response">HttpWebResponse对象</param>
        /// <returns>返回utf-8字符</returns>
        public static string getResponseString(HttpWebResponse response)
        {
            string json = null;
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding("UTF-8")))
            {
                try
                {
                    json = reader.ReadToEnd();
                }
                catch (Exception ex)
                {
                    Common.Log4.LogManage.WriteErr("getResponseString " + ex.Message);
                }
            }
            if (response != null)
            {
                response.Close();
                response.Dispose();
            }
            return json;
        }
        // 获取异常信息
        private static string getRestErrorMessage(HttpWebResponse errorResponse)
        {
            string errorhtml = "";
            try
            {
                errorhtml = getResponseString(errorResponse);
            }
            catch (Exception ex)
            {
                Common.Log4.LogManage.WriteErr("getRestErrorMessage " + ex.Message);
            }
            finally
            {
                if (errorResponse != null)
                {
                    errorResponse.Close();
                }
            }
            return errorhtml;
        }
        /// <summary>
        /// 将datas集合封装成json格式
        /// </summary>
        /// <param name="Datas">集合</param>
        /// <returns>json数据</returns>
        public static string GetJsonStr(Dictionary<string, string> Datas)
        {
            StringWriter sw = new StringWriter();
            JsonWriter writer = new JsonTextWriter(sw);

            writer.WriteStartObject();
            foreach (string item in Datas.Keys)
            {
                writer.WritePropertyName(item);
                writer.WriteValue(Datas[item]);
            }

            writer.WriteEndObject();
            writer.Flush();
            string jsonText = sw.GetStringBuilder().ToString();
            return jsonText;
        }
    }
}
